package edu.gyc.test;

import java.util.concurrent.Semaphore;

public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 13; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();

                    System.out.println(Thread.currentThread().getName() + "\t抢到车位"+semaphore.drainPermits());
                    Thread.sleep((long) (5000*Math.random()));
                    System.out.println(Thread.currentThread().getName() + "\t办事完毕，车位"+semaphore.drainPermits()+"空闲");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }
    }
}
